<?php
declare(strict_types=1);

namespace app\controller\api\admin\system;

use think\App;
use think\Request;
use think\exception\ValidateException;

use app\controller\api\ApiBaseController;
use app\logic\api\admin\system\UserLogic;
use app\validate\api\admin\system\UserValidate;

class UserController extends ApiBaseController
{
    protected UserLogic $logic;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->logic = new UserLogic();
    }

    public function index(Request $request)
    {
        $param = $request->param();

        $where = [];
        isset($param['username']) && $param['username'] != '' && $where[] = ['username', 'like', '%' . $param['username'] . '%'];
        isset($param['phone']) && $param['phone'] != '' && $where[] = ['phone', 'like', '%' . $param['phone'] . '%'];
        isset($param['status']) && $param['status'] != '' && $where[] = ['status', '=', $param['status']];
        isset($param['dept_id']) && $param['dept_id'] != '' && $where[] = ['dept_id', '=', $param['dept_id']];

        $lgc_re = $this->logic->list($where, '*', [], [], [
            'with' => [
                'dept' => function ($query) {
                    $query->field('id,name');
                }
            ],
            'hidden_fields' => ['salt', 'password', 'token', 'delete_time'],
        ]);

        return $lgc_re['code'] == 200
            ? $this->success($lgc_re['msg'], $lgc_re['data'])
            : $this->error($lgc_re['msg']);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'username' => '',
            'email' => '',
            'phone' => '',
            'password' => '',
            'dept_id',
            'nickname' => '',
            'avatar' => '',
            'sex' => '',
            'remark' => '',
            'status',
            'role_ids' => '',
        ]);
        $data['username'] = trim($data['username']) ?? '';
        $data['email'] = trim($data['email']) ?? '';
        $data['phone'] = trim($data['phone']) ?? '';
        $data['nickname'] = trim($data['nickname']) ?? '';
        $data['remark'] = trim($data['remark']) ?? '';

        try {
            validate(UserValidate::class)->scene('save')->check($data);

            $data['salt'] = \zhtp\Random::alnum(6);
            $data['password'] = password_md5($data['password'], $data['salt']);

            $lgc_re = $this->logic->save($data);

            return $lgc_re['code'] == 200
                ? $this->success($lgc_re['msg'])
                : $this->error($lgc_re['msg']);
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    public function read(Request $request, $id)
    {
        $lgc_re = $this->logic->read(['id' => $id]);

        return $lgc_re['code'] == 200
            ? $this->success($lgc_re['msg'], $lgc_re['data'])
            : $this->error($lgc_re['msg']);
    }

    public function update(Request $request, $id)
    {
        $data = $request->only([
            'username' => '',
            'email' => '',
            'phone' => '',
            'password' => '',
            'dept_id' => 0,
            'nickname' => '',
            'avatar' => '',
            'sex' => '',
            'remark' => '',
            'status',
            'role_ids' => null,
        ]);
        $data['id'] = $id;
        $data['username'] = trim($data['username']) ?? '';
        $data['email'] = trim($data['email']) ?? '';
        $data['phone'] = trim($data['phone']) ?? '';
        $data['nickname'] = trim($data['nickname']) ?? '';
        $data['remark'] = trim($data['remark']) ?? '';


        try {
            validate(UserValidate::class)->scene('update')->check($data);

            $lgc_re = $this->logic->update($data);

            return $lgc_re['code'] == 200
                ? $this->success($lgc_re['msg'])
                : $this->error($lgc_re['msg']);
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    public function delete($id)
    {
        $data = $this->request->only([
            'del_ids'
        ]);

        try {
            validate(UserValidate::class)->scene('delete')->check($data);

            $lgc_re = $this->logic->delete($data);

            return $lgc_re['code'] == 200
                ? $this->success($lgc_re['msg'])
                : $this->error($lgc_re['msg']);
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    public function mine(Request $request)
    {
        $lgc_re = $this->logic->mine(['id' => $request->x_token_user['id']]);

        return $lgc_re['code'] == 200
            ? $this->success($lgc_re['msg'], $lgc_re['data'])
            : $this->error($lgc_re['msg']);
    }

    public function mineUpdate(Request $request)
    {
        $data = $request->only([
            'username',
            'email',
            'phone',
            'avatar',
            'nickname',
            'sex',
            'description',
            // 'remark',
        ]);
        $data['username'] = trim($data['username']) ?? '';
        $data['email'] = trim($data['email']) ?? '';
        $data['phone'] = trim($data['phone']) ?? '';
        $data['nickname'] = trim($data['nickname']) ?? '';

        $data['id'] = $request->x_token_user['id']; // 只能修改自己

        try {
            validate(UserValidate::class)->scene('mineUpdate')->check($data);

            $lgc_re = $this->logic->mineUpdate($data);

            return $lgc_re['code'] == 200
                ? $this->success($lgc_re['msg'])
                : $this->error($lgc_re['msg']);
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    public function changePwd(Request $request)
    {
        $data = $request->only([
            'old_password' => '',
            'password' => '',
        ]);
        $data['id'] = $request->x_token_user['id']; // 只能修改自己的密码

        try {
            validate(UserValidate::class)->scene('changePwd')->check($data);

            $lgc_re = $this->logic->changePwd($data);

            return $lgc_re['code'] == 200
                ? $this->success($lgc_re['msg'])
                : $this->error($lgc_re['msg']);
        } catch (ValidateException $e) {
            return $this->error($e->getMessage());
        }
    }

    public function dataScope(Request $request)
    {
        $admin_auth = \app\library\api\admin\Auth::instance();
        $data_scope = $admin_auth->getDataScope($request->x_token_user['id']);

        return $this->success('获取成功', $data_scope);
    }
}
